package com.sjzd.server.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sjzd.server.pojo.Menu;
import com.sjzd.server.pojo.MenuRole;
import com.sjzd.server.pojo.RespBean;
import com.sjzd.server.pojo.Role;
import com.sjzd.server.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ZFQ
 * @date 2021/3/4
 */
@Api("权限组controller")
@RestController
@RequestMapping("/sys/basic/per")
public class PermissionController {
    @Autowired
    private IMenuRoleService menuRoleService;

    @Autowired
    private IMenuService menuService;

    @Autowired
    private IRoleService roleService;

    @ApiOperation("获取所有角色")
    @GetMapping("/")
    public List<Role> getAllRoles() {
        return roleService.list();
    }

    @ApiOperation("获取所有视图")
    @GetMapping("/menus")
    public List<Menu> getAllMenus() {
        return menuService.getMenusWithChildren();
    }

    @ApiOperation("根据角色id获取所拥护的视图id")
    @GetMapping("/mid/{rid}")
    public List<Integer> getMenusByRid(@PathVariable Integer rid) {
        List<MenuRole> menuRoles = menuRoleService.list(new QueryWrapper<MenuRole>().eq("rid", rid));
        return menuRoles.stream().map(MenuRole::getMid).collect(Collectors.toList());
    }

    @ApiOperation("添加角色")
    @PostMapping("/")
    public RespBean addRole(@RequestBody Role role) {
        if (!role.getName().startsWith("ROLE_")) {
            role.setName("ROLE_" + role.getName());
        }
        if (roleService.save(role)) {
            return RespBean.success("添加成功！");
        }
        return RespBean.error("添加失败！");
    }

    @ApiOperation("删除角色")
    @DeleteMapping("/")
    public RespBean delRole(Integer rid) {
        if (roleService.removeById(rid)) {
            return RespBean.success("删除成功！");
        }
        return RespBean.error("删除失败！");
    }


    @ApiOperation("更改用户权限")
    @PutMapping("/")
    public RespBean updPermission(Integer rid, Integer[] mids) {
        if (menuRoleService.updateMenusByRid(mids, rid)) {
            return RespBean.success("更改成功！");
        }
        return RespBean.error("更改失败！");
    }
}
